package cn.gailvlun.gll.presentation.chat;

import android.Manifest;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.FragmentPhotoBinding;
import cn.gailvlun.gll.presentation.base.BaseFragment;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.StringUtil;
import cn.gailvlun.gll.util.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;



public class PhotoFragment extends BaseFragment {

    public static PhotoFragment newInstance(String photoUrl, int position) {
        PhotoFragment photoFragment = new PhotoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url", photoUrl);
        bundle.putInt("position", position);
        photoFragment.setArguments(bundle);
        return photoFragment;
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    private FragmentPhotoBinding mBinding;
    private String photoUrl;
    private int position;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        photoUrl = getArguments().getString("url");
        position = getArguments().getInt("position", 0);

        fileName = StringUtil.getFileNameByUrl(photoUrl);
    }

    @Override
    protected View initComponent(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_photo, null, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBinding.pv.setTransitionName(getString(R.string.shared_image) + position);
        }
        mBinding.setPresenter(new Presenter());
        return mBinding.getRoot();
    }

    @Override
    protected void createHandler() {
    }

    private Bitmap mBitmap;
    private String fileName;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        Glide.with(mContext)
                .asBitmap()
                .load(photoUrl)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        getActivity().supportStartPostponedEnterTransition();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        getActivity().supportStartPostponedEnterTransition();
                        return false;
                    }
                })
                .into(new ImageViewTarget<Bitmap>(mBinding.pv) {
                    @Override
                    protected void setResource(@Nullable Bitmap resource) {
                        if (resource != null) {
                            mBitmap = resource;
                            mBinding.pv.setImageBitmap(resource);
                        }
                    }
                });
    }

    
    @Nullable
    public ImageView getImage() {
        if (mBinding != null) {
            return mBinding.pv;
        }
        return null;
    }

    public class Presenter {
        public void onClickImage() {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        }

        public boolean onLongClickImage(View view) {
            if (view instanceof ImageView) {
                DialogUtil.showHint(mContext, "是否保存该图片", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        new RxPermissions(getActivity())
                                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean aBoolean) throws Exception {
                                        if (aBoolean) {
                                            saveFile();
                                        } else {
                                            ToastUtil.showShort("没有权限");
                                        }
                                    }
                                });
                    }
                });
                return true;
            }
            return false;
        }
    }

    private void saveFile() {
        final File path = new File(Environment.getExternalStorageDirectory(), "gailvlun/images/");
        if (FileUtils.createOrExistsDir(path)) {
            File theSaveFile = new File(path, fileName);
            Single.just(theSaveFile)
                    .map(new Function<File, File>() {
                        @Override
                        public File apply(File file) throws Exception {
                            ImageUtils.save(mBitmap, file, Bitmap.CompressFormat.PNG);
                            saveToMedia(file);
                            return file;
                        }
                    })
                    .compose(RxUtil.<File>applySingleScheduler())
                    .subscribe(new SingleObserver<File>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(File file) {
                            FileUtils.deleteFile(file);
                            ToastUtil.showShort("保存成功");
                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastUtil.showShort("保存失败");
                        }
                    });
        }
    }

    private void saveToMedia(File file) {
        
        try {
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));
    }
}
